package com.hss.springboot3.controller;

import com.hss.springboot3.bean.UserEntity;
import com.hss.springboot3.jpa.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    UserJPA userJPA;


    @RequestMapping(value = "/list")
    public List<UserEntity> list(){
        return userJPA.findAll();
    }

    @RequestMapping(value = "/add")
    public String add()
    {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("测试");
        userEntity.setPassword("123456");
        userEntity.setMobile("133066824");
        userJPA.save(userEntity);
        return "用户信息添加成功";
    }

//http://127.0.0.1:8080/ageLarge?age=20
    @RequestMapping(value = "/ageLarge")
    public List<UserEntity> listAgeLarge(int age){

        return userJPA.ageLarge(age);
    }

    //http://127.0.0.1:8080/cutpage?page=1

    @RequestMapping(value = "/cutpage")
    public List<UserEntity> page(int page){

        UserEntity userEntity = new UserEntity();
        userEntity.setPage(2);
        userEntity.setSize(2);
        PageRequest pageRequest = new PageRequest(userEntity.getPage()-1,userEntity.getSize());
        return userJPA.findAll(pageRequest).getContent();
    }


    @RequestMapping(value = "/cutpagesort")
    public List<UserEntity> pageSoort(int page){

        UserEntity userEntity = new UserEntity();
        userEntity.setPage(page);
        userEntity.setSize(2);
        userEntity.setSord("desc");

        //获取排序对象
        Sort.Direction sort_direction = Sort.Direction.ASC.toString().equalsIgnoreCase(userEntity.getSord())?Sort.Direction.ASC:Sort.Direction.DESC;
        //设置排序对象参数
        Sort sort = new Sort(sort_direction, userEntity.getSidx());
        //创建分页对象
        PageRequest pageRequest = new PageRequest(userEntity.getPage() - 1,userEntity.getSize(),sort);



        return userJPA.findAll(pageRequest).getContent();
    }


}
